package cn.iocoder.yudao.module.handguard.service.productaccessitem;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.handguard.controller.admin.publicitytype.vo.PublicitySelectBaseVO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccess.ProductAccessDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.publicityselect.PublicitySelectDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.publicitytype.PublicityTypeDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.usertablesaudit.UserTablesAuditDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.productaccess.ProductAccessMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.publicityselect.PublicitySelectMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.publicitytype.PublicityTypeMapper;
import cn.iocoder.yudao.module.handguard.tool.DataConversionUtils;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.handguard.controller.admin.productaccessitem.vo.*;
import cn.iocoder.yudao.module.handguard.dal.dataobject.productaccessitem.ProductAccessItemDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.handguard.convert.productaccessitem.ProductAccessItemConvert;
import cn.iocoder.yudao.module.handguard.dal.mysql.productaccessitem.ProductAccessItemMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.handguard.enums.ErrorCodeConstants.*;

/**
 * 产品准入项 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ProductAccessItemServiceImpl implements ProductAccessItemService {

    @Resource
    private PublicityTypeMapper publicityTypeMapper;
    @Resource
    private ProductAccessMapper productAccessMapper;
    @Resource
    private PublicitySelectMapper publicitySelectMapper;
    @Resource
    private ProductAccessItemMapper productAccessItemMapper;

    @Override
    public Long createProductAccessItem(ProductAccessItemCreateReqVO createReqVO) {
        // 插入
        ProductAccessItemDO productAccessItem = ProductAccessItemConvert.INSTANCE.convert(createReqVO);
        productAccessItemMapper.insert(productAccessItem);
        // 返回
        return productAccessItem.getId();
    }

    @Override
    public void updateProductAccessItem(ProductAccessItemUpdateReqVO updateReqVO) {
        // 校验存在
        validateProductAccessItemExists(updateReqVO.getId());
        // 更新
        ProductAccessItemDO updateObj = ProductAccessItemConvert.INSTANCE.convert(updateReqVO);
        productAccessItemMapper.updateById(updateObj);
    }

    @Override
    public void deleteProductAccessItem(Long id) {
        // 校验存在
        LambdaUpdateWrapper<ProductAccessItemDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductAccessItemDO::getProductAccessId, id);
        // 删除
        productAccessItemMapper.delete(updateWrapper);
    }

    private void validateProductAccessItemExists(Long id) {
        if (productAccessItemMapper.selectById(id) == null) {
            throw exception(PRODUCT_ACCESS_ITEM_NOT_EXISTS);
        }
    }

    @Override
    public ProductAccessItemDO getProductAccessItem(Long id) {
        return productAccessItemMapper.selectById(id);
    }

    @Override
    public List<ProductAccessItemRespVO> getProductAccessItemList(Long id) {
        //LambdaQueryWrapperX<ProductAccessItemDO> queryWrapper = new LambdaQueryWrapperX<>();
        //queryWrapper.eq(ProductAccessItemDO::getProductAccessId, id);
        List<ProductAccessItemDO> doList = productAccessItemMapper.getProductAccessItemList(id);
        List<ProductAccessItemRespVO> itemList = ProductAccessItemConvert.INSTANCE.convertList(doList);
        itemList.forEach(i -> {

            //如果pid为空
            if (i.getPid()==null || i.getPid()==0) {
                i.setPid(productAccessItemMapper.getPid(i.getTypeNames(),i.getClassName()));
                //更新
                ProductAccessItemDO productAccessItemDO = new ProductAccessItemDO();
                BeanUtils.copyProperties(i, productAccessItemDO);
                productAccessItemMapper.updateById(productAccessItemDO);
            }

            if (i.getCategory().equals("207") || i.getCategory().equals("208")) {
                if (StringUtils.isNotEmpty(i.getResultValue())){
                    i.setValueArr(i.getResultValue().split(","));
                }
            }

            if (i.getCategory().equals("200")) {
                if (StringUtils.isNotEmpty(i.getResultValue())) {
                    if (i.getResultValue().startsWith("-1")){
                        String[] parts = i.getResultValue().split("-(?=.*-)");
                        String p = parts[1];
                        String one = "-1";
                        String two = p.split("-")[1];
                        i.setParam1(one);
                        i.setParam2(two);
                    }else {
                        if (i.getResultValue().contains("-")) {
                            String[] arrStr = i.getResultValue().split("-");
                            i.setParam1(arrStr[0]);
                            i.setParam2(arrStr[1]);
                        }
                    }
                }
            } else if (i.getCategory().equals("201")) {
                if (StringUtils.isNotEmpty(i.getResultValue())) {
                    if (i.getResultValue().contains("-")) {
                        String[] vArr = i.getResultValue().split("-");
                        i.setParam1(vArr[0]);
                        i.setParam2(vArr[1]);
                    }
//                    if (i.getResultValue().contains(",")) {
//                        String[] vArr = i.getResultValue().split(",");
//                        String[] arrStr1 = vArr[0].split("-");
//                        String[] arrStr2 = vArr[1].split("-");
//                        i.setParam1(arrStr1[0]);
//                        i.setParam2(arrStr1[1]);
//                        i.setParam3(arrStr2[0]);
//                        i.setParam4(arrStr2[1]);
//                    }
                }
            }
        });
        return itemList;
    }

    @Override
    public PageResult<ProductAccessItemDO> getProductAccessItemPage(ProductAccessItemPageReqVO pageReqVO) {
        return productAccessItemMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ProductAccessItemDO> getProductAccessItemList(ProductAccessItemExportReqVO exportReqVO) {
        return productAccessItemMapper.selectList(exportReqVO);
    }

    @Override
    public void saveProductAccessItemBatch(ProductAccessItemUpdateBatchReqVO updateReqVO) {
        //先删除
        productAccessItemMapper.deleteByPid(updateReqVO.getId());
        for (ProductAccessItemDO item : updateReqVO.getVoList()) {

            LambdaUpdateWrapper<PublicitySelectDO> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(PublicitySelectDO::getTypesName, item.getTypeNames());
            wrapper.eq(PublicitySelectDO::getClassName, item.getClassName());
            PublicitySelectDO publicitySelectDO = publicitySelectMapper.selectOne(wrapper);
            if (publicitySelectDO != null) {
                item.setPid(publicitySelectDO.getId());
            }

            if (item.getValueArr().length > 0) {
                item.setResultValue(String.join(",", item.getValueArr()));
            } else {
                //item.setResultValue("");
            }

             if (item.getCategory().equals("200")) {
                if (StringUtils.isEmpty(item.getParam1()) || StringUtils.isEmpty(item.getParam2())) {
                    throw exception(PARAM_NULL_ERROR);
                } else {
                    String param1 = item.getParam1();
                    String param2 = item.getParam2();
                    item.setResultValue(param1 + "-" + param2);
                }
            } else if (item.getCategory().equals("201")) {
                if (StringUtils.isEmpty(item.getParam1()) || StringUtils.isEmpty(item.getParam2())) {
                    throw exception(PARAM_NULL_ERROR);
                } else {
                    String param1 = item.getParam1();
                    String param2 = item.getParam2();
                   // String param3 = item.getParam3();
                  //  String param4 = item.getParam4();
                    item.setResultValue(param1 + "-" + param2);
                   // item.setResultValue(param1 + "-" + param2 + "," + param3 + "-" + param4);
                }
            }
        }
        productAccessItemMapper.insertBatch(updateReqVO.getVoList());
    }

    @Override
    public void updateProductAccessItemBatch(ProductAccessItemUpdateBatchReqVO updateReqVO) {
        productAccessItemMapper.updateBatch(updateReqVO.getVoList());
    }

    @Override
    public Map<String, List<ProductAccessItemDO>> getProductAccessItemGroupList(Long id) {
        LambdaQueryWrapperX<ProductAccessItemDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eq(ProductAccessItemDO::getProductAccessId, id);
        List<ProductAccessItemDO> list = productAccessItemMapper.selectList(queryWrapperX);

        //分组数据
        Map<String, List<ProductAccessItemDO>> listMap = DataConversionUtils.groupProductAccessByStream(list);

        ProductAccessItemConvert.INSTANCE.convertList(list);
        return listMap;
    }


}
